<?php
namespace app\common;

class TaobaoApi
{
  private $secret,$app_key;
  public function __construct()
  {
    $bseele = getSettingType('饿了么');
    $this->secret = $bseele['ele_appkey'];
    $this->app_key = $bseele['ele_appid'];
    // $this->secret = '159c6593a562fd8d853cd7a3aa87645e';
    // $this->app_key = '28319359';
  }
  public function get($method ='',$query = array())
  {
    $timestamp = date('Y-m-d H:i:s', time());
    $query['app_key'] = $this->app_key;
    $query['sign_method'] = 'md5';
    $query['method'] = $method;
    $query['format'] = 'json';
    $query['timestamp'] = $timestamp;
    $query['v'] = '2.0';
    $sign = $this->getSign($query);

    $timestamp = date('Y-m-d H:i:s', time());
    $query['timestamp'] = $timestamp;
    ksort($query);
    $query['sign'] = $sign;
    $post = http_build_query($query);
    
    $url='http://gw.api.taobao.com/router/rest?'.$post;
    $res = $this->request($url);
    // $r = json_encode($res,JSON_PRETTY_PRINT);
    // $data=stripslashes($r);
    // json_decode()
    return json_decode($res,true);
  }
  //拼接签名
  public function getSign($query = '')
  {
    ksort($query);
    $signstr = '';
    if (is_array($query)) {
      foreach ($query as $key => $value) {
        if ($value == '') continue;
        $signstr .= $key . $value;
      }
    }
    $sign = md5($this->secret.$signstr.$this->secret);
    $sign = strtoupper($sign);
    return $sign;
  }

  public function request($url = '',$data=null)
  {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
  }
}